#include <fstream>
#include <QRegExp>
#include "bankclinetconfig.h"

using namespace std;

void
BankClinetConfig::init()
{
    //首先是从默认路径读取配置
    ifstream fin(confFilePath_.toStdString().c_str());
    if(fin) {
        QString segmentName;
        QString propertyName;
        QString key,val;
        string line;
        QRegExp rx;
        while (getline(fin, line))
        {
            //首先要对[xxxx]这种格式进行匹配，表明这个是一
            //个大项，前面最多允许有\s符号
            rx.setPattern("^\\s*\\[[^\\]]+\\]");
            if(rx.exactMatch(line.c_str())) {
                //获取到大部名字
                segmentName = line.c_str();
                rx.setPattern("\\s+");
                segmentName.replace(rx,"");
                rx.setPattern("[\\[|\\]]+");
                segmentName.replace(rx,"");
                continue;
            }
            //对单个属性进行记录 key = val
            rx.setPattern("^\\s*[\\w|\\d]+\\s*=\\s*[^=]+");
            if(rx.exactMatch(line.c_str())) {
                propertyName = line.c_str();
                rx.setPattern("\\s+");
                propertyName.replace(rx,"");
                rx.setPattern("(.*)=(.*)");
                if(propertyName.indexOf(rx) >= 0) {
                    key = segmentName + "-" + rx.cap(1);
                    val = rx.cap(2);
                }
                confMap_[key] = val;
            }
        }
        fin.close();
    }
    //配置文件如果不全，一些配置就使用默认配置进行补全
    readDefaultConf();
}

void
BankClinetConfig::readDefaultConf()
{
    //直接将一些默认配置注册进去，已有就不在注册
    const char *key[] = {"CLIENT-SERVER_IP","CLIENT-PORT"};
    const char *val[] = {"192.168.0.101","8888"};
    map<QString,QString>::const_iterator it;
    for(quint32 i;i < sizeof(key) / sizeof(key[0]);++i) {
        it = confMap_.find(key[i]);
        if(it == confMap_.end()) {
            confMap_.insert(make_pair(key[i],val[i]));
        }
    }
}

bool
BankClinetConfig::getConf(QString &key,QString &val)
{
    map<QString,QString>::const_iterator it;
    it = confMap_.find(key);
    if(it != confMap_.end()) {
        val = it->second;
        return true;
    }
    return false;
}

bool
BankClinetConfig::setConf(QString &key, QString &val)
{
    map<QString,QString>::const_iterator it;
    it = confMap_.find(key);
    if(it != confMap_.end()) {
        confMap_.erase(key);
    }
    confMap_.insert(make_pair(key,val));
    //通知进行更新操作
    notify();
    return true;
}

bool
BankClinetConfig::addDelegate(notityFunc_ f)
{
    confNotifyDelegateList_.push_back(f);
    return true;
}

void
BankClinetConfig::notify()
{
    list<notityFunc_>::const_iterator it;
    for(it = confNotifyDelegateList_.begin();
        it != confNotifyDelegateList_.end();++it) {
        (*it)();//执行通知操作
    }
}
